/**
 * 844. 比较含退格的字符串
 * https://leetcode-cn.com/problems/backspace-string-compare/
 */
public class Solutions_844 {
    public static void main(String[] args) {
//        String S = "ab#c", T = "ad#c";  // output: true
//        String S = "ab##", T = "c#d#";  // output: true
//        String S = "a##c", T = "#a#c";  // output: true
        String S = "a#c", T = "b";  // output: false

        boolean result = backspaceCompare(S, T);
        System.out.println(result);
    }

    public static boolean backspaceCompare(String S, String T) {
        // 两个字符串都转化为退格后，用 equals 比较
        String s1 = convert(S);
        String t1 = convert(T);
        return s1.equals(t1);
    }

    public static String convert(String str) {
        char[] arr = str.toCharArray();
        int len = arr.length;
        char[] ans = new char[len];
        int idx = 0;
        for (int i = 0; i < len; i++) {
            if (arr[i] == '#') {
                // 如果对空文本输入退格字符，文本继续为空。
                idx = idx == 0 ? 0 : idx - 1;
            } else {
                ans[idx++] = arr[i];
            }
        }
        return String.copyValueOf(ans, 0, idx);
    }
}
